package cn.sc.summer.construction.sysimpl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import cn.sc.summer.constant.rabbit.RabbitConstant;
import cn.sc.summer.daoapi.dao.GatewayLogMapper;
import cn.sc.summer.mybatis.annotation.dynamicdatasource.DataSource;
import cn.sc.summer.mybatis.enums.DataSourceEnum;
import cn.sc.summer.rabbitmq.enums.RabbitErrorMessageTypeEnum;
import cn.sc.summer.rabbitmq.po.GatewayLog;
import cn.sc.summer.rabbitmq.po.RabbitMessage;
import cn.sc.summer.rabbitmq.service.RabbitConsumerService;
import cn.sc.summer.rabbitmq.util.RabbitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 类名：网关日志监听入库
 *
 * @author a-xin
 * @date 2024/2/5 11:40
 */
@Slf4j
@Service
public class GatewayLogImpl extends RabbitConsumerService {

    @Resource
    private GatewayLogMapper gatewayLogMapper;

    /**
     * 接口: 网关日志监听入库
     *
     * @param jsonStr 日志信息
     * @param message rabbit消息提
     * @param channel rabbit信道
     * @author a-xin
     * @date 2023/9/23 15:48
     */
    @DataSource(DataSourceEnum.POST_GRE_SQL)
    @RabbitListener(queues = RabbitConstant.GATEWAY_LOG_QUEUE)
    public void consumer(String jsonStr, Message message, Channel channel) {
        try {
            RabbitMessage<GatewayLog> gatewayLogRabbitMessage = RabbitUtil.checkMessage(jsonStr, new TypeReference<GatewayLog>() {
            });
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            if (gatewayLogRabbitMessage.getFlag()) {
                gatewayLogMapper.insert(gatewayLogRabbitMessage.getMessage());
            } else {
                log.error("==> 接收到重复消费消息：Queue: {}, Exchange : {}, RoutingKey : {}, Message : {}",
                        RabbitConstant.GATEWAY_LOG_QUEUE,
                        RabbitConstant.GATEWAY_LOG_EXCHANGE,
                        RabbitConstant.GATEWAY_LOG_ROUTING_KEY,
                        jsonStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            rabbitErrorService.exchangeMessage(e.getMessage(), jsonStr, RabbitErrorMessageTypeEnum.GATEWAY_LOG_WRITE_ERROR);
        }
    }

}
